// @ts-ignore
/* eslint-disable */
import { message } from "antd";
import TokenManager from "@/token";
import { request } from "@umijs/max";
import type { API } from "@/types/api";
import { postRefreshToken } from "@/services/core/api";

// 公共Token验证方法
async function validateToken(navigate: any): Promise<boolean> {
    const accessToken = TokenManager.getAccessToken();
    const isInvalidAccessToken = [
        null,
        "",
        " [object Promise]",
        "null",
    ].includes(accessToken);
    if (!isInvalidAccessToken) {
        const refreshToken = TokenManager.getRefreshToken();
        const isInvalidRefreshToken = [
            null,
            "",
            " [object Promise]",
            "null",
        ].includes(refreshToken);
        if (isInvalidRefreshToken) {
            console.log("refresh_token过期！");
            // navigate("/login");
            window.location.reload();
            await postRefreshToken(navigate);
        }
        return false;
    }
    return true;
}

export async function postAllNodesList(
    node_id: string,
    navigate?: any,
): Promise<API.PostAllNodesListResult> {
    await validateToken(navigate);

    return await request<API.PostAllNodesListResult>(
        `/api/core/node/nodes_list?node_id=${node_id}`,
        {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                Authorization: "Bearer " + TokenManager.getAccessToken(),
            },
        },
    )
        .then((res) => {
            return res;
        })
        .catch(async (err: any) => {
            if (err.response.data.status_code === "EXPIRED_TOKEN") {
                console.log("触发token刷新！");
                await postRefreshToken(navigate);
                return await postAllNodesList(node_id, navigate);
            } else {
                message.error(err.response.data.message);
                return err.response.data;
            }
        });
}

export async function postBindInfo(navigate?: any): Promise<any> {
    await validateToken(navigate);

    return await request<API.PostJarContextResult>(`/api/core/node/bind_info`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            Authorization: "Bearer " + TokenManager.getAccessToken(),
        },
    })
        .then((res) => {
            return res;
        })
        .catch(async (err: any) => {
            if (err.response.data.status_code === "EXPIRED_TOKEN") {
                console.log("触发token刷新！");
                await postRefreshToken(navigate);
                return await postBindInfo(navigate);
            } else {
                message.error(err.response.data.message);
                return err.response.data;
            }
        });
}

export async function postNewBind(data: any, navigate?: any): Promise<any> {
    await validateToken(navigate);

    return await request<API.PostJarContextResult>(`/api/core/node/bind_new`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            Authorization: "Bearer " + TokenManager.getAccessToken(),
        },
        data: data,
    })
        .then((res) => {
            return res;
        })
        .catch(async (err: any) => {
            if (err.response.data.status_code === "EXPIRED_TOKEN") {
                console.log("触发token刷新！");
                await postRefreshToken(navigate);
                return await postNewBind(data, navigate);
            } else {
                message.error(err.response.data.message);
                return err.response.data;
            }
        });
}

export async function postUnBindNode(data: any, navigate?: any): Promise<any> {
    await validateToken(navigate);

    return await request<API.PostJarContextResult>(
        `/api/core/node/unbind_node`,
        {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                Authorization: "Bearer " + TokenManager.getAccessToken(),
            },
            data: data,
        },
    )
        .then((res) => {
            return res;
        })
        .catch(async (err: any) => {
            if (err.response.data.status_code === "EXPIRED_TOKEN") {
                console.log("触发token刷新！");
                await postRefreshToken(navigate);
                return await postUnBindNode(data, navigate);
            } else {
                message.error(err.response.data.message);
                return err.response.data;
            }
        });
}

export async function postReaload(node_id: string, navigate?: any): Promise<any> {
    await validateToken(navigate);

    return await request<API.PostJarContextResult>(
        `/api/apps/system/info/reaload?node_id=${node_id}`,
        {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                Authorization: "Bearer " + TokenManager.getAccessToken(),
            },
        },
    )
        .then((res) => {
            return res;
        })
        .catch(async (err: any) => {
            if (err.response.data.status_code === "EXPIRED_TOKEN") {
                console.log("触发token刷新！");
                await postRefreshToken(navigate);
                return await postReaload(node_id, navigate);
            } else {
                message.error(err.response.data.message);
                return err.response.data;
            }
        });
}

/**
 * 获取节点基础信息（除系统负载外的所有信息）
 * @param navigate 
 * @returns 
 */
export async function postBasicInfo(node_id: string, navigate?: any): Promise<any> {
    await validateToken(navigate);

    return await request<API.PostJarContextResult>(
        `/api/core/nodes/basic_info?node_id=${node_id}`,
        {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                Authorization: "Bearer " + TokenManager.getAccessToken(),
            },
        },
    )
        .then((res) => {
            return res;
        })
        .catch(async (err: any) => {
            if (err.response.data.status_code === "EXPIRED_TOKEN") {
                console.log("触发token刷新！");
                await postRefreshToken(navigate);
                return await postBasicInfo(node_id, navigate);
            } else {
                message.error(err.response.data.message);
                return err.response.data;
            }
        });
}
